# 序列化分类名称

from rest_framework import serializers

from users.models import User
from django.contrib.auth.hashers import make_password


# 序列化用户模型
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = [
            'id',
            'username',
            'mobile',
            'email',

            'password',
        ]

        # 更改字段约束
        extra_kwargs = {
            # password 设置为只参与反序列化
            'password': {'write_only': True, 'min_length': 8, 'max_length': 20},
            'username': {'min_length': 3, 'max_length': 20}
        }

    # 第一种：对有效参数进行校验
    def validate(self, attrs):
        attrs['is_staff'] = True
        # 明文密码
        raw_password = attrs.get('password')
        # 密文密码
        attrs['password'] = make_password(raw_password)

        return attrs

    # # 重写create
    # def create(self, validated_data):
    #     # 在有效数据中添加is_staff=True
    #     validated_data['is_staff'] = True
    #     user = User.objects.create_user(**validated_data)
    #     return user
